<!-- views/reports/CustomerHabitsReport.vue -->
<template>
  <div class="customer-habits-report">
    <!-- 报告头部 -->
    <el-card class="report-header">
      <template #header>
        <div class="header-content">
          <div class="header-left">
            <h2>
              <el-icon class="title-icon"><User /></el-icon>
              客户习惯分析
            </h2>
            <div class="report-info">
              <el-tag type="success">自动生成</el-tag>
              <span class="last-update">最后更新: {{ lastUpdate }}</span>
            </div>
          </div>
          <div class="header-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="loadReport"
            />
            <el-button type="primary" :icon="Refresh" @click="generateReport" :loading="loading">
              生成报告
            </el-button>
            <el-button :icon="Download" @click="exportReport">
              导出报告
            </el-button>
          </div>
        </div>
      </template>
    </el-card>

    <!-- 客户习惯概览 -->
    <el-row :gutter="20" class="stats-overview">
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#1890ff' }">
              <el-icon><ShoppingCart /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ formatNumber(statistics.avgPurchaseFrequency) }}</div>
              <div class="stat-label">平均购买频次</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#52c41a' }">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.avgPurchaseInterval }}</div>
              <div class="stat-label">平均购买间隔(天)</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#722ed1' }">
              <el-icon><Coin /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatCurrency(statistics.avgOrderAmount) }}</div>
              <div class="stat-label">平均客单价</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#fa8c16' }">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.customerRetentionRate }}%</div>
              <div class="stat-label">客户留存率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 客户行为分析 -->
    <el-row :gutter="20" class="behavior-section">
      <el-col :span="16">
        <el-card class="behavior-card">
          <template #header>
            <div class="card-header">
              <span>客户购买时间分布</span>
            </div>
          </template>
          <div class="behavior-content">
            <div class="time-distribution">
              <div class="distribution-item" v-for="item in timeDistribution" :key="item.period">
                <div class="period">{{ item.period }}</div>
                <el-progress 
                  :percentage="item.percentage" 
                  :stroke-width="20" 
                  :show-text="false"
                  :color="getProgressColor(item.percentage)"
                />
                <div class="percentage">{{ item.percentage }}%</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="summary-card">
          <template #header>
            <div class="card-header">
              <span>客户生命周期</span>
            </div>
          </template>
          <div class="summary-content">
            <div class="lifecycle-item" v-for="item in customerLifecycle" :key="item.stage">
              <div class="stage">{{ item.stage }}</div>
              <div class="count">{{ formatNumber(item.count) }}人</div>
              <div class="percentage">{{ item.percentage }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 客户分群分析 -->
    <el-row :gutter="20" class="segmentation-section">
      <el-col :span="12">
        <el-card class="segmentation-card">
          <template #header>
            <div class="card-header">
              <span>RFM客户分群</span>
            </div>
          </template>
          <div class="segmentation-content">
            <el-table :data="rfmSegments" style="width: 100%">
              <el-table-column prop="segment" label="客户群体" width="120" />
              <el-table-column prop="count" label="客户数" width="100" />
              <el-table-column prop="percentage" label="占比">
                <template #default="{ row }">
                  {{ row.percentage }}%
                </template>
              </el-table-column>
              <el-table-column prop="characteristics" label="特征描述" />
            </el-table>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="segmentation-card">
          <template #header>
            <div class="card-header">
              <span>购买偏好分析</span>
            </div>
          </template>
          <div class="segmentation-content">
            <el-table :data="purchasePreferences" style="width: 100%">
              <el-table-column prop="category" label="商品类别" width="120" />
              <el-table-column prop="orderCount" label="订单数" width="100" />
              <el-table-column prop="salesAmount" label="销售金额">
                <template #default="{ row }">
                  ¥{{ formatCurrency(row.salesAmount) }}
                </template>
              </el-table-column>
              <el-table-column prop="customerCount" label="客户数" width="100" />
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from '@vue/runtime-core'
import { 
  ElMessage, 
  ElNotification 
} from 'element-plus'
import { 
  User,
  Refresh, 
  Download, 
  ShoppingCart,
  Timer,
  Coin,
  Star
} from '@element-plus/icons-vue'

// 导入API
import { customerHabitsAPI } from '@/api/customerHabits'

// 数据模型
interface Statistics {
  avgPurchaseFrequency: number
  avgPurchaseInterval: number
  avgOrderAmount: number
  customerRetentionRate: number
}

interface TimeDistribution {
  period: string
  percentage: number
}

interface CustomerLifecycle {
  stage: string
  count: number
  percentage: number
}

interface RFMSegment {
  segment: string
  count: number
  percentage: number
  characteristics: string
}

interface PurchasePreference {
  category: string
  orderCount: number
  salesAmount: number
  customerCount: number
}

// 响应式数据
const dateRange = ref<string[]>([])
const loading = ref(false)
const lastUpdate = ref('')

const statistics = ref<Statistics>({
  avgPurchaseFrequency: 0,
  avgPurchaseInterval: 0,
  avgOrderAmount: 0,
  customerRetentionRate: 0
})

const timeDistribution = ref<TimeDistribution[]>([])
const customerLifecycle = ref<CustomerLifecycle[]>([])
const rfmSegments = ref<RFMSegment[]>([])
const purchasePreferences = ref<PurchasePreference[]>([])

// 方法
const formatCurrency = (amount: number): string => {
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

const formatNumber = (num: number): string => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toString()
}

const loadReport = async () => {
  loading.value = true
  try {
    // 调用API获取客户习惯分析数据
    const params = {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    }
    
    const result = await customerHabitsAPI.getCustomerHabits(params)
    
    if (result.success && result.data) {
      // 更新统计数据
      statistics.value = {
        avgPurchaseFrequency: result.data.statistics?.avgPurchaseFrequency || 0,
        avgPurchaseInterval: result.data.statistics?.avgPurchaseInterval || 0,
        avgOrderAmount: result.data.statistics?.avgOrderAmount || 0,
        customerRetentionRate: result.data.statistics?.customerRetentionRate || 0
      }
      
      // 更新时间分布数据
      timeDistribution.value = result.data.timeDistribution || []
      
      // 更新客户生命周期数据
      customerLifecycle.value = result.data.customerLifecycle || []
      
      // 更新RFM分群数据
      rfmSegments.value = result.data.rfmSegments || []
      
      // 更新购买偏好数据
      purchasePreferences.value = result.data.purchasePreferences || []
      
      // 更新时间
      lastUpdate.value = new Date().toLocaleString('zh-CN')
      
      ElMessage.success('客户习惯分析数据加载成功')
    } else {
      ElMessage.error(result.message || '获取客户习惯分析数据失败')
    }
  } catch (error) {
    ElMessage.error('客户习惯分析数据加载失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

const generateReport = async () => {
  await loadReport()
}

const exportReport = () => {
  // 模拟导出报告
  ElMessage.success('客户习惯分析报告导出成功!')
}

const getProgressColor = (percentage: number) => {
  if (percentage >= 30) return '#52c41a'
  if (percentage >= 20) return '#1890ff'
  return '#fa8c16'
}

// 组件挂载时加载数据
onMounted(() => {
  // 设置默认日期范围为最近30天
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)
  
  dateRange.value = [
    startDate.toISOString().split('T')[0],
    endDate.toISOString().split('T')[0]
  ]
  
  // 加载初始数据
  loadReport()
})
</script>

<style scoped lang="scss">
.customer-habits-report {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
  
  .report-header {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    
    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-left {
        h2 {
          margin: 0;
          font-size: 24px;
          font-weight: 600;
          color: #303133;
          display: flex;
          align-items: center;
          gap: 8px;
          
          .title-icon {
            color: #409eff;
          }
        }
        
        .report-info {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-top: 8px;
          
          .last-update {
            font-size: 14px;
            color: #909399;
          }
        }
      }
      
      .header-actions {
        display: flex;
        gap: 12px;
        align-items: center;
      }
    }
  }
  
  .stats-overview {
    margin-bottom: 20px;
    
    .stat-card {
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
      }
      
      .stat-content {
        display: flex;
        align-items: center;
        padding: 20px;
        
        .stat-icon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;
          
          .el-icon {
            font-size: 24px;
            color: white;
          }
        }
        
        .stat-info {
          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 4px;
          }
          
          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .behavior-section {
    margin-bottom: 20px;
    
    .behavior-card, .summary-card {
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      
      .card-header {
        font-weight: 600;
        color: #303133;
      }
    }
    
    .behavior-content {
      padding: 20px 0;
      
      .time-distribution {
        .distribution-item {
          display: flex;
          align-items: center;
          margin-bottom: 16px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .period {
            width: 120px;
            font-size: 14px;
            color: #606266;
          }
          
          .percentage {
            width: 50px;
            text-align: right;
            font-size: 14px;
            color: #303133;
            font-weight: 500;
          }
        }
      }
    }
    
    .summary-content {
      padding: 20px 0;
      
      .lifecycle-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .stage {
          font-size: 14px;
          color: #606266;
        }
        
        .count, .percentage {
          font-size: 16px;
          font-weight: 500;
          color: #303133;
        }
      }
    }
  }
  
  .segmentation-section {
    .segmentation-card {
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      
      .card-header {
        font-weight: 600;
        color: #303133;
      }
      
      .segmentation-content {
        padding: 16px 0;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .customer-habits-report {
    padding: 12px;
    
    .report-header {
      .header-content {
        flex-direction: column;
        gap: 16px;
        align-items: stretch;
      }
    }
    
    .stats-overview {
      .el-col {
        margin-bottom: 12px;
      }
    }
    
    .behavior-section {
      .el-col {
        margin-bottom: 12px;
      }
    }
    
    .segmentation-section {
      .el-col {
        margin-bottom: 12px;
      }
    }
  }
}
</style>